package com.bestcem.xm.ticket.controller;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.common.core.enums.ResourceErrorCodeEnum;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.component.security.dto.TokenDTO;
import com.bestcem.xm.ticket.controller.param.ExportTicketParam;
import com.bestcem.xm.ticket.controller.vo.ticket.TicketInfoVO;
import com.bestcem.xm.ticket.controller.vo.ticket.TicketPageVO;
import com.bestcem.xm.ticket.enums.TicketStatusEnum;
import com.bestcem.xm.ticket.service.TicketService;
import com.bestcem.xm.ticket.service.dto.DatetimeFilter;
import com.bestcem.xm.ticket.service.dto.FileDTO;
import com.bestcem.xm.ticket.service.dto.PageDTO;
import com.bestcem.xm.ticket.service.dto.RegionFilter;
import com.bestcem.xm.ticket.service.dto.dashboard.DashboardDTO;
import com.bestcem.xm.ticket.service.dto.ticket.DeleteTicketDTO;
import com.bestcem.xm.ticket.util.AuthorityUtil;
import com.bestcem.xm.ticket.util.CommonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 工单接口
 *
 * @author XiaoYunSong <ys.xiao@idiaoyan.com>
 * @version v2.0
 * @date 2021/8/16 11:49
 */
@Slf4j
@Api(tags = "tickets")
@RestController
@RequestMapping(value = "/ticket/tickets", produces = MediaType.APPLICATION_JSON_VALUE)
public class TicketTicketsController {

    @Resource
    private TicketService ticketService;

    @Resource
    private CommonUtils commonUtils;

    @Resource
    private HttpServletRequest request;

    @Resource
    private AuthorityUtil authorityUtil;

    /**
     * 导出工单2.3版本
     *
     * @param param
     * @return
     */
    @GetMapping(value = "/export")
    public XmResultJson<FileDTO> downloadTicket2_3(ExportTicketParam param) {
        String orgId = SecurityContextHolder.getOrgId();
        String userId = SecurityContextHolder.getUserId();

        if (!ObjectId.isValid(orgId)) {
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_FORMAT, "公司id格式错误");
        }

        TokenDTO token = SecurityContextHolder.getToken();

        param.setOrgId(orgId);
        param.setUserId(userId);
        if (Objects.nonNull(token)) {
            param.setSuperAdmin(token.getSuperRole());
        }

        ServiceResult<FileDTO> serviceResult = ticketService.export(param);
        if (serviceResult.isSuccess()) {
            return XmResultJson.success(serviceResult.getData());
        }
        return XmResultJson.fail(serviceResult.getErrorData(), serviceResult.getMsg());
    }

    /**
     * 获取最近七天新增工单图表信息
     *
     * @return com.bestcem.xm.util.XmResultJson 七天新增工单图表信息
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/8/27 16:07
     */
    @GetMapping(value = "/dashboard")
    public XmResultJson<DashboardDTO> getStaticsInfo() {


        String orgId = SecurityContextHolder.getOrgId();
        String userId = SecurityContextHolder.getUserId();
        TokenDTO token = SecurityContextHolder.getToken();
        boolean isSuper = false;
        if (Objects.nonNull(token)) {
            isSuper = Integer.valueOf(1).equals(token.getSuperRole());
        }

        RegionFilter regionFilter = new RegionFilter();
        regionFilter.setOrgId(orgId);
        regionFilter.setStatus(TicketStatusEnum.DELETED);
        regionFilter.setSuper(isSuper);
        long start = System.currentTimeMillis();
        if (!isSuper) {
            regionFilter.setRegions(commonUtils.getUserAllRegions(userId));
            log.warn("[Ticket] ticket getStaticsInfo grpc 耗时1 {}", System.currentTimeMillis() - start);
            regionFilter.setUserId(userId);
            regionFilter.setRoleIds(commonUtils.getUserAllRoleId(userId));
            log.warn("[Ticket] ticket getStaticsInfo grpc 耗时2 {}", System.currentTimeMillis() - start);
        }
        ServiceResult<DashboardDTO> result = ticketService.getDashboardData(regionFilter, new DatetimeFilter());
        if (result.isSuccess()) {
            return XmResultJson.success(result.getData());
        }

        return XmResultJson.fail(result.getErrorData(), result.getMsg());
    }


    /**
     * 获取单个工单
     */
    @GetMapping("/{id}")
    public XmResultJson<TicketInfoVO> getTicket(@PathVariable String id) {
        // id存在时,获取单个工单的相关信息
        if (!ObjectId.isValid(id)) {
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_FORMAT, "id格式不正确");
        }

        String userId = SecurityContextHolder.getUserId();

        TokenDTO token = SecurityContextHolder.getToken();
        // 水平权限校验
        boolean hasPermission = authorityUtil.hasLookPermission(id, token);
        if (!hasPermission) {
            return XmResultJson.fail(ResourceErrorCodeEnum.PERMISSION_DENY, "当前用户无权限查看该工单");
        }

        ServiceResult<TicketInfoVO> result = ticketService.getTicketInfo(id, userId);
        if (!result.isSuccess()) {
            return XmResultJson.fail(result.getErrorData(), result.getMsg());
        }
        return XmResultJson.success(result.getData());
    }

    /**
     * 获取工单列表
     */
    @GetMapping("/")
    public XmResultJson<PageDTO<TicketPageVO>> pageTicket(ExportTicketParam param) {
        // 替换搜索输入里面的特殊字符
        if (!ObjectUtils.isEmpty(param.getSearch())) {
            param.setSearch(CommonUtils.escapeRegexChar(param.getSearch()));
        }

        String orgId = SecurityContextHolder.getOrgId();
        String userId = SecurityContextHolder.getUserId();
        TokenDTO token = SecurityContextHolder.getToken();

        param.setOrgId(orgId);
        param.setUserId(userId);
        if (Objects.nonNull(token)) {
            param.setSuperAdmin(token.getSuperRole());
        }

        if (Objects.isNull(param.getPage()) || Objects.isNull(param.getRowsPerPage())) {
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_LOST, "参数缺失");
        }
        ServiceResult<PageDTO<TicketPageVO>> result = ticketService.pageTickets(param);
        if (!result.isSuccess()) {
            return XmResultJson.fail(result.getErrorData(), result.getMsg());
        }
        return XmResultJson.success(result.getData());
    }

    /**
     * 删除工单
     *
     * @param id 工单id
     * @return 删除的数量
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/8/26 15:11
     */
    @ApiOperation(value = "删除工单")
    @DeleteMapping(value = "/{id}")
    public XmResultJson<DeleteTicketDTO> deleteTicket(@PathVariable(required = false) String id) {
        if (Objects.isNull(id)) {
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_LOST, "工单id不能为空");
        }
        if (!ObjectId.isValid(id)) {
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_FORMAT, "工单id错误");
        }
        ServiceResult<Long> serviceResult = ticketService.deleteTicket(id);
        if (serviceResult.isSuccess()) {
            return XmResultJson.success(new DeleteTicketDTO(serviceResult.getData()));
        }
        return XmResultJson.fail(serviceResult.getErrorData(), serviceResult.getMsg());
    }

}
